/* Android-Michi is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by the Free Software Foundation; either version 2 of the License,
 * or (at your option) any later version.
 *
 * Android-Michi is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Android-Michi; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
*/

package model;

public class HumanTicTacToe {
	
	char grid[][];
	public boolean winner = false;
	
	public HumanTicTacToe() {
		grid = new char[3][3];
		reset();
	}
	
	public  void reset() {
		winner = false;
		for (int i=0;i<3;i++)
			for (int j=0;j<3;j++)
				grid[i][j]= ' ';
	}
	
	public boolean store(int x, int y, char player) {
		if (winner) return false;
		if (grid[x][y] == ' ') {
			grid[x][y] = player;
			return true;
		}
		else
			return false;
	} 
	
	public boolean checkForWinner(char player) {
		winner = checkPlayer(player);
		return winner;
	}
	private boolean checkPlayer(char player) {
		// check columns and rows
		boolean _winner = true;
		
		for (int i=0;i<3;i++) {
			_winner = true;
			for (int j=0;j<3;j++)
				if (grid[i][j]!= player)
					_winner = false;
			if (_winner) 
				return true;
 		}
		_winner = true; 
		
		for (int i=0;i<3;i++) {
			_winner=true;
			for (int j=0;j<3;j++)
			{
				if (grid[j][i]!= player)
					_winner = false;
			}
			if (_winner) 
				return true;
 		}
		_winner = true; 
		
		
		//check diagonal 
		if (grid[1][1]!=player) return false;  // have to have the center square
		
		if (grid[0][0] == player && grid[2][2] == player) return true;
		
		if (grid[0][2] == player && grid[2][0] == player) return true;
		
		return false;
	}
}
